package me.jiatao.wan.common.ui

import android.content.Context
import android.util.AttributeSet
import androidx.constraintlayout.motion.widget.MotionLayout
import com.google.android.material.appbar.AppBarLayout

/**
 * @Author: taojia
 * @CreateDate: 2021/8/25 2:22 下午
 * @Version: 1.0
 * @Description:
 */

class CollapsibleToolbar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : MotionLayout(context, attrs, defStyleAttr), AppBarLayout.OnOffsetChangedListener {

    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        progress = -verticalOffset / appBarLayout?.totalScrollRange?.toFloat()!!
    }

    /**
     * 当判定父组件是AppBarLayout时，添加addOnOffsetChangedListener接口
     * 当onAttachedToWindow调用后，如果不实现addOnOffsetChangedListener接口编译报错
     */
    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        (parent as? AppBarLayout)?.addOnOffsetChangedListener(this)
    }
}